package com.thinkfit.jy.fragment;

import android.graphics.Paint;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.common.lib.bean.VideoBean;
import com.common.lib.bean.VideoTagBean;
import com.common.lib.constant.Constants;
import com.common.lib.constant.EventBusEvent;
import com.common.lib.fragment.BaseFragment;
import com.common.lib.manager.DataManager;
import com.common.lib.utils.BaseUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.thinkfit.jy.R;
import com.thinkfit.jy.activity.VideoCourseInfoActivity;
import com.thinkfit.jy.adapter.VideoCourseAdapter;
import com.thinkfit.jy.contract.VideoListContract;
import com.thinkfit.jy.presenter.VideoListPresenter;
import com.thinkfit.jy.serialport.SerialPortManager;
import com.thinkfit.jy.utils.BluetoothOrder;
import com.thinkfit.jy.utils.DeviceTypeUtils;
import com.thinkfit.jy.utils.EquipmentInfoUtils;
import com.thinkfit.jy.utils.LogUtils;
import com.thinkfit.jy.utils.MotionDataUtils;
import com.thinkfit.jy.view.SpaceItemDecoration;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * 视频列表界面
 */
public class VideoListFragment extends BaseFragment<VideoListContract.Presenter> implements VideoListContract.View, OnRefreshLoadMoreListener {

    private VideoCourseAdapter mAdapter;
    private int mIndex;
    private int minTime = 0;
    private int maxTime = 0;
    private int mPage;
    private int mType,vType;
    int start = 0;
    int vtagid = 0;
    SpaceItemDecoration decoration;
    ConstraintLayout clFiltrate;

    TextView tvGoalAll,
            tvDifficultyAll,tvDifficulty1,tvDifficulty2,tvDifficulty3,tvDifficulty4,tvDifficulty5,
            tvTimeAll,tvTime1,tvTime2,tvTime3,tvTime4,tvTime5;
    LinearLayout llGoal;

    ArrayList<TextView> goalList = new ArrayList<>();
    ArrayList<TextView> difficultyList = new ArrayList<>();
    ArrayList<TextView> timeList = new ArrayList<>();
    ArrayList<VideoTagBean> videoTagBeanList = new ArrayList<>();

    @NonNull
    @Override
    protected VideoListContract.Presenter onCreatePresenter() {
        return new VideoListPresenter(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_video_list;
    }

    @Override
    protected void initView(@NonNull View view, @Nullable Bundle savedInstanceState) {
        mIndex = getArguments().getInt(Constants.BUNDLE_EXTRA);
        vType = getArguments().getInt(Constants.BUNDLE_EXTRA_2);
        mType = DeviceTypeUtils.getDeviceType();

        clFiltrate = view.findViewById(R.id.cl_filtrate);
        tvGoalAll = view.findViewById(R.id.tv_goal_all);
        tvDifficultyAll = view.findViewById(R.id.tv_difficulty_all);
        tvDifficulty1 = view.findViewById(R.id.tv_difficulty_1);
        tvDifficulty2 = view.findViewById(R.id.tv_difficulty_2);
        tvDifficulty3 = view.findViewById(R.id.tv_difficulty_3);
        tvDifficulty4 = view.findViewById(R.id.tv_difficulty_4);
        tvDifficulty5 = view.findViewById(R.id.tv_difficulty_5);
        tvTimeAll = view.findViewById(R.id.tv_time_all);
        tvTime1 = view.findViewById(R.id.tv_time_1);
        tvTime2 = view.findViewById(R.id.tv_time_2);
        tvTime3 = view.findViewById(R.id.tv_time_3);
        tvTime4 = view.findViewById(R.id.tv_time_4);
        tvTime5 = view.findViewById(R.id.tv_time_5);
        llGoal = view.findViewById(R.id.ll_goal);

        tvGoalAll.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
        tvDifficultyAll.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
        tvTimeAll.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);

        tvGoalAll.setOnClickListener(this);
        tvDifficultyAll.setOnClickListener(this);
        tvDifficulty1.setOnClickListener(this);
        tvDifficulty2.setOnClickListener(this);
        tvDifficulty3.setOnClickListener(this);
        tvDifficulty4.setOnClickListener(this);
        tvDifficulty5.setOnClickListener(this);
        tvTimeAll.setOnClickListener(this);
        tvTime1.setOnClickListener(this);
        tvTime2.setOnClickListener(this);
        tvTime3.setOnClickListener(this);
        tvTime4.setOnClickListener(this);
        tvTime5.setOnClickListener(this);

        initDifficulty();
        initTime();

        if(vType == 4){
            clFiltrate.setVisibility(View.GONE);
            sceneryTime(mIndex);
        }
        getPresenter().getVideoCourse(mIndex,minTime,maxTime, vType, 1,start,vtagid);//获取对于的视频播放列表
        RecyclerView recyclerView = view.findViewById(R.id.recyclerView);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 3);
        gridLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(gridLayoutManager);

        if(decoration != null){
            recyclerView.removeItemDecoration(decoration);
            decoration = null;
        }

        int screenWidth = BaseUtils.StaticParams.dp2px(getActivity(),790) - BaseUtils.StaticParams.dp2px(getActivity(),20)*2;// 23  recycleView 左右缩进距离
        int totalSpace=(screenWidth- BaseUtils.StaticParams.dp2px(getActivity(),245)*3);//  55 item宽度
        System.out.println("ddddddddddddddddddddddd  screenWidth : "+screenWidth+"  totalSpace : "+totalSpace);
        decoration = new SpaceItemDecoration(totalSpace,getActivity(),3);
        recyclerView.addItemDecoration(decoration);

        getAdapter().onAttachedToRecyclerView(recyclerView);
        recyclerView.setAdapter(getAdapter());
        SmartRefreshLayout layout = view.findViewById(R.id.smartRefreshLayout);
        layout.setOnRefreshLoadMoreListener(this);
        layout.autoRefresh();
        layout.setEnableLoadMore(false);
        getAdapter().setNewInstance(
                DataManager.Companion.getInstance().getVideoList(mType, mIndex));
        finishLoad();
        mPage = 0;
    }
    public void initGoal(){
        VideoTagBean videoTagBean = new VideoTagBean();
        videoTagBean.setEntagname("All");
        videoTagBean.setTagname(getString(R.string.app_all));
        videoTagBean.setId(0);
        videoTagBeanList.add(videoTagBean);
        goalList.add(tvGoalAll);
    }
    public void initDifficulty(){
        difficultyList.add(tvDifficultyAll);
        difficultyList.add(tvDifficulty1);
        difficultyList.add(tvDifficulty2);
        difficultyList.add(tvDifficulty3);
        difficultyList.add(tvDifficulty4);
        difficultyList.add(tvDifficulty5);
    }
    public void initTime(){
        timeList.add(tvTimeAll);
        timeList.add(tvTime1);
        timeList.add(tvTime2);
        timeList.add(tvTime3);
        timeList.add(tvTime4);
        timeList.add(tvTime5);
    }
    private VideoCourseAdapter getAdapter() {
        if (mAdapter == null) {
            mAdapter = new VideoCourseAdapter(getActivity());
            mAdapter.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                    VideoBean bean = mAdapter.getItem(position);
                    System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa    vType : "+vType);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable(Constants.BUNDLE_EXTRA, bean);
                    bundle.putSerializable(Constants.BUNDLE_EXTRA_2, vType);
//                    openActivity(mType == 1 ? VideoCourseDetailActivity.class : LiveVideoActivity.class, bundle);
                    openActivity(VideoCourseInfoActivity.class, bundle);
                }
            });
        }
        return mAdapter;
    }

    @Override
    public void onResume() {
        super.onResume();
        getPresenter().getVideoTag();


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tv_goal_all:
                vtagid = 0;
                refreshTextView(goalList,tvGoalAll);
                getPresenter().getVideoCourse(mIndex,minTime,maxTime, vType, 1,start,vtagid);
                break;
            case R.id.tv_difficulty_all:
                start = 0;
                refreshTextView(difficultyList,tvDifficultyAll);
                getPresenter().getVideoCourse(mIndex,minTime,maxTime, vType, 1,start,vtagid);
                break;
            case R.id.tv_difficulty_1:
                start = 1;
                refreshTextView(difficultyList,tvDifficulty1);
                getPresenter().getVideoCourse(mIndex,minTime,maxTime, vType, 1,start,vtagid);
                break;
            case R.id.tv_difficulty_2:
                start = 2;
                refreshTextView(difficultyList,tvDifficulty2);
                getPresenter().getVideoCourse(mIndex,minTime,maxTime, vType, 1,start,vtagid);
                break;
            case R.id.tv_difficulty_3:
                start = 3;
                refreshTextView(difficultyList,tvDifficulty3);
                getPresenter().getVideoCourse(mIndex,minTime,maxTime, vType, 1,start,vtagid);
                break;
            case R.id.tv_difficulty_4:
                start = 4;
                refreshTextView(difficultyList,tvDifficulty4);
                getPresenter().getVideoCourse(mIndex,minTime,maxTime, vType, 1,start,vtagid);
                break;
            case R.id.tv_difficulty_5:
                start = 5;
                refreshTextView(difficultyList,tvDifficulty5);
                getPresenter().getVideoCourse(mIndex,minTime,maxTime, vType, 1,start,vtagid);
                break;
            case R.id.tv_time_all:
                mIndex = 0;
                refsehTime(mIndex);
                refreshTextView(timeList,tvTimeAll);
                getPresenter().getVideoCourse(mIndex,minTime,maxTime, vType, 1,start,vtagid);
                break;
            case R.id.tv_time_1:
                mIndex = 1;
                refsehTime(mIndex);
                refreshTextView(timeList,tvTime1);
                getPresenter().getVideoCourse(mIndex,minTime,maxTime, vType, 1,start,vtagid);
                break;
            case R.id.tv_time_2:
                mIndex = 2;
                refsehTime(mIndex);
                refreshTextView(timeList,tvTime2);
                getPresenter().getVideoCourse(mIndex,minTime,maxTime, vType, 1,start,vtagid);
                break;
            case R.id.tv_time_3:
                mIndex = 3;
                refsehTime(mIndex);
                refreshTextView(timeList,tvTime3);
                getPresenter().getVideoCourse(mIndex,minTime,maxTime, vType, 1,start,vtagid);
                break;
            case R.id.tv_time_4:
                mIndex = 4;
                refsehTime(mIndex);
                refreshTextView(timeList,tvTime4);
                getPresenter().getVideoCourse(mIndex,minTime,maxTime, vType, 1,start,vtagid);
                break;
            case R.id.tv_time_5:
                mIndex = 5;
                refsehTime(mIndex);
                refreshTextView(timeList,tvTime5);
                getPresenter().getVideoCourse(mIndex,minTime,maxTime, vType, 1,start,vtagid);
                break;

        }
    }

    public void refreshTextView(ArrayList<TextView> list,TextView textView){
        for (int y = 0;y<list.size();y++){
            list.get(y).setTextColor(getContext().getColor(R.color.color_FFF9EF));
            list.get(y).getPaint().setFlags(0);
//                        if(goalList.get(y).getId() == v.getId()){
//                            goalList.get(y).setTextColor(getContext().getColor(R.color.color_D8A051));
//
//                        }else {
//                            goalList.get(y).setTextColor(getContext().getColor(R.color.color_FFF9EF));
//                        }
        }
        textView.setTextColor(getContext().getColor(R.color.color_D8A051));
        textView.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
    }

    @Override
    public void getVideoCourseSuccess(int page, ArrayList<VideoBean> list) {
        if (getView() == null) {
            return;
        }
        mPage = page;
        if (page == 1) {
            getAdapter().setNewInstance(list);
        } else {
            getAdapter().addData(list);
        }
        finishLoad();
    }

    @Override
    public void getVideoCourseFailed() {
        if (getView() == null) {
            return;
        }
        finishLoad();
    }

    @Override
    public void getVideoTagSuccess(ArrayList<VideoTagBean> list) {
        llGoal.removeAllViews();
        videoTagBeanList.clear();
        goalList.clear();

        initGoal();
        for (int i = 0;i< list.size();i++){
            videoTagBeanList.add(list.get(i));
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            params.setMargins(58, 0, 0, 0); // left, top, right, bottom margins
            TextView textView = new TextView(getContext());
            if(DataManager.Companion.getInstance().getLanguage() == 0){
                textView.setText(list.get(i).getTagname());
            }else {
                textView.setText(list.get(i).getEntagname());
            }
            if(vtagid == list.get(i).getId()){
                textView.setTextColor(getContext().getColor(R.color.color_D8A051));
                textView.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);

            }else {
                textView.setTextColor(getContext().getColor(R.color.color_FFF9EF));
                textView.getPaint().setFlags(0);
            }
            textView.setTextSize(13);
            textView.setLayoutParams(params);
            textView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    for (int y = 0;y<goalList.size();y++){
                        goalList.get(y).setTextColor(getContext().getColor(R.color.color_FFF9EF));
                        goalList.get(y).getPaint().setFlags(0);
                        if(textView.getText().toString().equals(goalList.get(y).getText().toString())){
                            vtagid = videoTagBeanList.get(y).getId();
                        }

                    }
                    textView.setTextColor(getContext().getColor(R.color.color_D8A051));
                    textView.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
                    getPresenter().getVideoCourse(mIndex,minTime,maxTime, vType, 1,start,vtagid);
                }
            });
            goalList.add(textView);
            llGoal.addView(textView);
        }

    }

    @Override
    public void onReceive(@NonNull HashMap<String, Object> map) {
        if (map == null) {
            return;
        }
        if ( map.containsKey(EventBusEvent.PAUSE_RUN)||map.containsKey(EventBusEvent.STOP_RUN)){
            if(DeviceTypeUtils.isConnect()){
                if(MotionDataUtils.getInstance().isRun()){

//                    stopDevice();
                }
            }
        }else {
            super.onReceive(map);
        }

    }

    public void stopDevice(){
        if(!(SerialPortManager.getInstance().isConnected() || BluetoothOrder.getInstance().isConnect())){
            System.out.println("ddddddddddddddddddddddd   未连接设备 1");
            return;
        }
        if(DeviceTypeUtils.connectDeviceType() == 0){//判断连接类型
            BluetoothOrder.getInstance().closeRxJavaClone();
            if(EquipmentInfoUtils.getInstance().isPause()){
                System.out.println("ddddddddddddddddddddddd   蓝牙通知设备暂停");
                BluetoothOrder.getInstance().bluetoothOrderWrite(BluetoothOrder.EQUIPMENT_PAUSE);
            }else {
                System.out.println("ddddddddddddddddddddddd   蓝牙通知设备停止");
                BluetoothOrder.getInstance().bluetoothOrderWrite(BluetoothOrder.EQUIPMENT_STOP);
            }
        }else {
            if(EquipmentInfoUtils.getInstance().isPause()){
                System.out.println("ddddddddddddddddddddddd   串口通知设备暂停");
                SerialPortManager.getInstance().pauseRun();
            }else {
                System.out.println("ddddddddddddddddddddddd   串口通知设备停止");
                SerialPortManager.getInstance().stopRun();
            }

        }
    }

    private void finishLoad() {
        SmartRefreshLayout layout = getView().findViewById(R.id.smartRefreshLayout);
        layout.finishLoadMore();
        layout.finishRefresh();
        layout.setEnableLoadMore(getAdapter().getItemCount() != 0
                && getAdapter().getItemCount() % 9 == 0);
        if (getAdapter().getItemCount() == 0) {
            setViewGone(R.id.recyclerView);
            setViewVisible(R.id.tvNoCourse);
        } else {
            setViewVisible(R.id.recyclerView);
            setViewGone(R.id.tvNoCourse);
        }
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        getPresenter().getVideoCourse(mIndex,minTime, maxTime, vType, mPage + 1,start,vtagid);
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        getPresenter().getVideoCourse(mIndex,minTime, maxTime, vType, 1,start,vtagid);
    }

    public static VideoListFragment getInstance(int index, int type) {
        Bundle bundle = new Bundle();
        bundle.putInt(Constants.BUNDLE_EXTRA, index);
        bundle.putInt(Constants.BUNDLE_EXTRA_2, type);
        VideoListFragment fragment = new VideoListFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    public void sceneryTime(int mIndex){
        switch (mIndex){
            case 0:
                minTime = 0;
                maxTime = 0;
                break;
            case 1:
                minTime = 0;
                maxTime = 10;
                break;
            case 2:
                minTime = 11;
                maxTime = 20;
                break;
            case 3:
                minTime = 21;
                maxTime = 30;
                break;

        }
    }

    public void refsehTime(int mIndex){
        switch (mIndex){
            case 0:
                minTime = 0;
                maxTime = 0;
                break;
            case 1:
                minTime = 0;
                maxTime = 15;
                break;
            case 2:
                minTime = 16;
                maxTime = 25;
                break;
            case 3:
                minTime = 26;
                maxTime = 35;
                break;
            case 4:
                minTime = 36;
                maxTime = 45;
                break;
            case 5:
                minTime = 46;
                maxTime = 999;
                break;

        }
    }

    protected int dp2px(float dpValue) {
        float density = getContext().getResources().getDisplayMetrics().density;
        return (int) (dpValue * density + 0.5f);
    }
}
